package com.gxuwz.endrskyweather.viewmodel;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.gxuwz.endrskyweather.apiclient.CheckUpdateClient;

public class AppInfoViewModel extends AndroidViewModel {

    private CheckUpdateClient updateClient;

    private MutableLiveData<Integer> resultCode;

    public AppInfoViewModel(@NonNull Application application) {
        super(application);
        updateClient = new CheckUpdateClient();
        resultCode = new MutableLiveData<>();
    }

    public MutableLiveData<Integer> getResultCode() {
        return resultCode;
    }

    /**
     * 检查更新
     * 返回状态码：0-检查更新成功，1-检查更新失败，2-当前版本已是最新版本
     * @return
     */
    public void doCheckUpdate(Context context) {
        new Thread(() -> {
            try {
                String latestVersion = updateClient.checkVersion();
                Log.d("AppInfoViewModel", "获取到的版本号：" + latestVersion);
                if (latestVersion == null) {
                    // 最新版本号为空，说明检查更新失败
                    resultCode.postValue(1);
                    return;
                }
                // 获取当前版本号
                String currentVersion = getApplication().getPackageManager().getPackageInfo(getApplication().getPackageName(), 0).versionName;
                if (latestVersion.equals(currentVersion)) {
                    // 当前版本已是最新版本
                    resultCode.postValue(2);
                    return;
                }
                // 下载更新
                updateClient.downloadUpdates(context, latestVersion);
                resultCode.postValue(0);
            } catch (Exception e) {
                Log.e("AppInfoFragment", "检查更新失败", e);
                resultCode.postValue(1);
            }
        }).start();
    }


}
